import json
from rest_framework.exceptions import ValidationError
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, filters
from rest_framework.generics import GenericAPIView
from apps.backend import models
from .serializers import PageNumberPagination, AdminMoldeSerializer, AdminMoldeUpdateSerializer
from drf_template_admin.services.RedisService import redis_connection
    
class AdminListView(GenericAPIView):
    queryset = models.SystemAdmin.objects.all().order_by("id")
    serializer_class = AdminMoldeSerializer 
    pagination_class = PageNumberPagination
    filter_backends = [filters.SearchFilter, ] 
    search_fields = ["username", "name", "is_active"]    

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            list = self.get_serializer(instance=page, many=True)
            result = self.get_paginated_response(list.data)
            return Response({'status': status.HTTP_200_OK, "data": result, 'message': 'success'})

    def post(self, request, *args, **kwargs):
        redisConnection = redis_connection('token')
        redis_token = json.loads(redisConnection.get_redis(request.auth))
        request.data['scope'] = redis_token['scope'] - 16
        ser = AdminMoldeSerializer(data=request.data)
        if not ser.is_valid():
            raise ValidationError({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "50001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_201_CREATED, "data":[], 'message': 'success'})  


class AdminDetailView(APIView):
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            queryset = models.SystemAdmin.objects.get(id=pk)
        except models.SystemAdmin.DoesNotExist:
            raise ValidationError({"status":status.HTTP_400_BAD_REQUEST, "errorCode": "50002", "errorMessage": '数据不存在'}) 
        
        ser = AdminMoldeUpdateSerializer(instance=queryset, data=request.data)
        if not ser.is_valid():
            raise ValidationError({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "50001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_200_OK, "data": [], 'message': 'put success'})  

    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        
        try:
            queryset = models.SystemAdmin.objects.get(id=pk)
        except models.SystemAdmin.DoesNotExist:
           raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "50002", "errorMessage": "数据不存在"})
        
        queryset.is_active = True if queryset.is_active==False else False 
        message = "删除成功" if queryset.is_active==False else "恢复成功"
        queryset.save()  

        return Response({'status': status.HTTP_200_OK, "data": [], 'message': message})     